<template>
  <div>
    <CategorySelector
      @changeCategory="changeCategory"
      :isShowList="isShowList"
    ></CategorySelector>
    <!-- 这个是列表界面 -->
    <div v-show="isShowList">
      <el-card style="margin-top: 20px">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!category3Id"
          @click="showAddDiv"
          >添加属性</el-button
        >

        <el-table style="width: 100%" border :data="attrList">
          <el-table-column label="序号" width="80" type="index" align="center">
          </el-table-column>

          <el-table-column prop="attrName" label="属性名称" width="150">
          </el-table-column>

          <el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{ row, $index }">
              <el-tag
                type="success"
                v-for="(attrValue, index) in row.attrValueList"
                :key="attrValue.id"
              >
                {{ attrValue.valueName }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="prop" label="操作" width="150">
            <template slot-scope="{ row, $index }">
              <HintButton
                icon="el-icon-edit"
                type="warning"
                size="mini"
                title="修改"
                @click="isShowUpdateDiv(row)"
              ></HintButton>
              <el-popconfirm
                :title="`确定删除${row.attrName}吗？`"
                @onConfirm="deleteAttr(row)"
              >
                <HintButton
                  slot="reference"
                  title="删除"
                  icon="el-icon-delete"
                  type="danger"
                  size="mini"
                ></HintButton>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 这个是修改或者添加界面 -->
    <div v-show="!isShowList" style="margin-top: 20px">
      <el-card>
        <el-form :model="attrForm" :inline="true">
          <el-form-item label="属性名">
            <el-input
              v-model="attrForm.attrName"
              placeholder="请输入属性名"
            ></el-input>
          </el-form-item>
        </el-form>

        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addAttrValue"
          :disabled="!attrForm.attrName"
          >添加属性值</el-button
        >
        <el-button @click="isShowList = true">取消</el-button>

        <el-table
          style="width: 100%; margin: 20px 0"
          border
          :data="attrForm.attrValueList"
        >
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称" width="width">
            <template slot-scope="{ row, $index }">
              <el-input
                :ref="$index"
                @blur="toLook(row)"
                @keyup.enter.native="toLook(row)"
                v-if="row.isEdit"
                v-model="row.valueName"
                size="mini"
              ></el-input>
              <span
                v-else
                @click="toEdit(row, $index)"
                style="display: block; width: 100%"
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>

          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-popconfirm
                :title="`确定要删除${row.valueName}吗？`"
                @onConfirm="attrForm.attrValueList.splice($index, 1)"
              >
                <HintButton
                  slot="reference"
                  title="删除"
                  icon="el-icon-delete"
                  type="danger"
                  size="mini"
                ></HintButton>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <el-button
          type="primary"
          @click="save"
          :disabled="!attrForm.attrValueList.length"
          >保存</el-button
        >
        <el-button @click="isShowList = true">取消</el-button>
      </el-card>
    </div>
  </div>
</template>

<script>
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "Attr",
  data() {
    return {
      category1Id: "",
      category2Id: "",
      category3Id: "",
      attrList: [],
      isShowList: true,

      attrForm: {
        attrName: "",
        attrValueList: [
          // {
          //   attrId: 0,
          //   id: 0,
          //   valueName: "string",
          // },
        ],
        categoryId: "",
        categoryLevel: 3,
      },
    };
  },
  methods: {
    changeCategory({ categoryId, level }) {
      if (level === 1) {
        this.category2Id = "";
        this.category3Id = "";
        this.attrList = [];
        this.category1Id = categoryId;
      } else if (level === 2) {
        this.category3Id = "";
        this.attrList = [];
        this.category2Id = categoryId;
      } else {
        this.category3Id = categoryId;
        //发请求获取属性列表
        this.getAttrList();
      }
    },
    async getAttrList() {
      let { category1Id, category2Id, category3Id } = this;
      try {
        const result = await this.$API.attr.getList(
          category1Id,
          category2Id,
          category3Id
        );
        if (result.code === 20000 || result.code === 200) {
          this.attrList = result.data;
        } else {
          this.$message.error("获取商品属性列表失败");
        }
      } catch (error) {
        this.$message.error("请求获取商品属性列表失败");
      }
    },
    //点击添加属性按钮显示添加属性界面
    showAddDiv() {
      this.isShowList = false;
      //清空attrForm
      this.attrForm = {
        attrName: "",
        attrValueList: [],
        categoryId: this.category3Id,
        categoryLevel: 3,
      };
    },
    //点击添加属性值
    addAttrValue() {
      this.attrForm.attrValueList.push({
        attrId: this.attrForm.id,
        valueName: "",
        isEdit: true,
      });
      this.$nextTick(() => {
        this.$refs[this.attrForm.attrValueList.length - 1].focus();
      });
    },
    //点击修改
    isShowUpdateDiv(row) {
      this.isShowList = false;
      this.attrForm = cloneDeep(row);
      this.attrForm.attrValueList.forEach((item) =>
        this.$set(item, "isEdit", false)
      );
    },
    // 当用户输入属性值名称完成后回车或者失去焦点的时候变成查看状态
    toLook(row) {
      // 1.添加的属性值名称不能为空
      let valueName = row.valueName;
      if (!valueName.trim()) {
        // this.$message.error("属性值名称不能为空白");
        row.valueName = "";
        return;
      }

      //2.添加的属性值名称不能重复
      let isRepeat = this.attrForm.attrValueList.some((item) => {
        //判断和自己不能相等
        if (item !== row) {
          return item.valueName === valueName.trim();
        }
      });

      if (isRepeat) {
        this.$message.error("属性值名称不能重复");
        row.valueName = "";
        return;
      }

      row.isEdit = false;
    },
    //当用户编辑 即属性值名称状态从查看状态变为编辑状态
    toEdit(row, index) {
      row.isEdit = true;
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },

    //点击保存按钮发送请求
    async save() {
      // 收集数据
      let attr = this.attrForm;
      //处理数据
      // 1.属性值如果为空串需要将属性值从列表中去除
      //2.去除添加的Edit属性
      attr.attrValueList = attr.attrValueList.filter((item) => {
        if (item.valueName.trim()) {
          delete item.isEdit;
          return true;
        }
      });
      //3.属性列表如果没有属性值不发请求
      if (!attr.attrValueList.length) {
        return;
      }
      //发请求
      try {
        const result = await this.$API.attr.addOrUpdate(attr);
        if (result.code === 20000 || result.code === 200) {
          this.$message.success("保存成功");
          this.isShowList = true;
          this.getAttrList();
        } else {
          this.$message.error("保存失败");
        }
      } catch (error) {
        this.$message.error("请求保存失败");
      }
    },
    //点击删除按钮发送请求
    async deleteAttr(row) {
      try {
        const result = await this.$API.attr.remove(row.id);
        if (result.code === 20000 || result.code === 200) {
          this.$message.success("删除成功");
          this.getAttrList();
        } else {
          this.$message.error("删除失败");
        }
      } catch (error) {
        this.$message.error("请求删除失败");
      }
    },
  },
};
</script>

<style scoped>
</style>